package dimension.starry.dataManager;

import dimension.starry.StarryDimension;
import dimension.starry.player.AttrbuteService;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.client.MinecraftClient;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import net.minecraft.world.World;

/**
 * @author 150149
 */
public class NetWorkRegister {

    private static final Identifier LIVING_PACKET_ID = new Identifier(StarryDimension.MOD_ID, "living");
    private static final Identifier ADD_ATTRIBUTE_PACKET_ID = new Identifier(StarryDimension.MOD_ID, "add_attribute");

    public static void onInitialize() {
        ServerPlayNetworking.registerGlobalReceiver(
            LIVING_PACKET_ID, (server, player, handler, buf, responseSender) -> {
                server.execute(() -> {
                    NbtCompound nbtCompound = PlayerDataManager.getSinglePlayerData(
                        server.getOverworld(), player.getName().getString());
                    responseSender.sendPacket(LIVING_PACKET_ID, PacketByteBufs.create().writeNbt(nbtCompound));
                });
            });
        ServerPlayNetworking.registerGlobalReceiver(
            ADD_ATTRIBUTE_PACKET_ID, (server, player, handler, buf, responseSender) -> {
                String attributeName = buf.readString();
                server.execute(() -> AttrbuteService.tryAddAttribute(player, attributeName));
            });
    }

    @Environment(EnvType.CLIENT)
    public static void onInitializeClient() {
        ClientPlayNetworking.registerGlobalReceiver(LIVING_PACKET_ID, (client, handler, buf, responseSender) -> {
            NbtCompound nbtCompound = buf.readNbt();
            client.execute(() -> PlayerDataManager.setClientPlayerData(nbtCompound));
        });
    }

    @Environment(EnvType.CLIENT)
    public static void sendLivingPacket() {
        ClientPlayNetworking.send(LIVING_PACKET_ID, PacketByteBufs.empty());
    }

    @Environment(EnvType.CLIENT)
    public static void sendAddAttributePacket(String attributeName) {
        ClientPlayNetworking.send(ADD_ATTRIBUTE_PACKET_ID, PacketByteBufs.create().writeString(attributeName));
    }

}
